﻿#region Using Statements

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

#endregion


namespace Freeform
{
    /// <summary>
    /// The world class maintains the state of a world that can be rendered to a screen via a viewport.
    /// </summary>
    public class World : Component
    {

        #region Members

        /// <summary>
        /// Gets a list of all components that are controlled directly by this world.
        /// </summary>
        public virtual ComponentList ComponentList { get; private set; }


        /// <summary>
        /// Gets the viewports that belong to this world.
        /// </summary>
        public virtual List<Viewport2D> Viewports { get; private set; }


        /// <summary>
        /// Gets or sets the background colour of the world.
        /// </summary>
        public virtual Color BackgroundColour { get; set; }


        /// <summary>
        /// Gets the process properties for the collision detection routine.
        /// </summary>
        public virtual ProcessProperties CollisionDetection { get; private set; }


        /// <summary>
        /// Determines the method of handling mutual collisions.
        /// </summary>
        public CollisionChecks CollisionChecks { get; set; }

        #endregion


        #region Init

        /// <summary>
        /// Creates a new 2d world.
        /// </summary>
        /// <param name="game">A reference to the game instance.</param>
        public World(Freeform.Game game) 
            : base(game.ComponentList)
        {
            ComponentList = new ComponentList(Game);
            Viewports = new List<Viewport2D>();
            CollisionDetection = new ProcessProperties();
            CollisionDetection.ProcessHandling = ProcessHandling.Sequential;
            CollisionChecks = Freeform.CollisionChecks.Mutual;
            Game.Worlds.Add(this);
        }

        #endregion


        #region Update

        /// <summary>
        /// Allows the world to update itself.
        /// </summary>
        /// <param name="time">Provides a snapshot of timing values.</param>
        public override void Update(GameTime time)
        {
            // Update entity list.
            ComponentList.UpdateLists();

            // Update the viewports that observe this world.
            for (int i = 0; i < Viewports.Count; i++)
                if (Viewports[i].IsEnabled && !Viewports[i].Disposed)
                    Viewports[i].Update(time);

            // Update the entities in the world.
            for (int i = 0; i < ComponentList.Loaded.Count; i++)
                if (ComponentList.Loaded[i].IsEnabled && !ComponentList.Loaded[i].Disposed)
                    ComponentList.Loaded[i].Update(time);

            // Collision detection.
            if (CollisionDetection.ProcessHandling == ProcessHandling.Sequential)
                CheckCollisions();

#if XBOX
#else
            // Multithreaded collision detection.
            else if (CollisionDetection.ProcessHandling == ProcessHandling.Multithread)
            {
                if (CollisionDetection.Thread == null || CollisionDetection.Thread.ThreadState != ThreadState.Running) 
                {
                    CollisionDetection.Thread = new Thread(CheckCollisions);
                    CollisionDetection.Thread.Start();
                }
            }
#endif

            base.Update(time);
        }

        #endregion


        #region Dispose

        /// <summary>
        /// Disposes this world and removes it from the game.
        /// </summary>
        protected override void OnDispose()
        {
            base.OnDispose();

            // Dispose all viewports.
            while (Viewports.Count > 0)
                Viewports[0].Dispose();

            // Dispose all entities in this world.
            for (int i = 0; i < ComponentList.All.Count; i++)
                ComponentList.All[i].Dispose();

            // Remove this world from the game.
            Game.Worlds.Remove(this);
        }

        #endregion


        #region Utility

        /// <summary>
        /// Iterates through each entity checking if it has collided with another entity.
        /// </summary>
        public virtual void CheckCollisions()
        {
            for (Int32 i = 0; i < ComponentList.ActiveColliders.Count; i++)
            {
                // If mutual collisions are on, we only check from i + 1.
                Int32 j = 0;
                if (CollisionChecks != Freeform.CollisionChecks.TwoWay)
                    j = i + 1;

                // Check collisions against other active entities.
                for (; j < ComponentList.ActiveColliders.Count; j++)
                    if (i != j)
                        if (ComponentList.ActiveColliders[i].CollisionProperties.CheckCollision(
                            ComponentList.ActiveColliders[j].CollisionProperties))
                            ComponentList.ActiveColliders[i].CollisionProperties.FireCollision(ComponentList.ActiveColliders[j], CollisionChecks == Freeform.CollisionChecks.Mutual);

                // Reset j for passive collision entities.
                j = 0;

                // Check collisions against other passive entities.
                for (; j < ComponentList.PassiveColliders.Count; j++)
                    if (ComponentList.ActiveColliders[i].CollisionProperties.CheckCollision(
                        ComponentList.PassiveColliders[j].CollisionProperties))
                        ComponentList.ActiveColliders[i].CollisionProperties.FireCollision(ComponentList.PassiveColliders[j], CollisionChecks == Freeform.CollisionChecks.Mutual);
            }
        }

        #endregion

    }
}